package weaver.jobs.holyview.duss;

import com.engine.common.util.ServiceUtil;
import com.engine.workflow.constant.PAResponseCode;
import com.engine.workflow.entity.publicApi.PAResponseEntity;
import com.engine.workflow.entity.publicApi.ReqOperateRequestEntity;
import com.engine.workflow.entity.publicApi.WorkflowDetailTableInfoEntity;
import com.engine.workflow.entity.requestForm.ReqFlowFailMsgEntity;
import com.engine.workflow.publicApi.WorkflowRequestOperatePA;
import com.engine.workflow.publicApi.impl.WorkflowRequestOperatePAImpl;
import weaver.common.DateUtil;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.interfaces.schedule.BaseCronJob;
import weaver.workflow.webservices.WorkflowRequestTableField;
import weaver.workflow.webservices.WorkflowRequestTableRecord;

import java.util.*;

import static weaver.common.DateUtil.getDateTime;


/**
 * @Title: ecology
 * @Company: weaver
 * @author: weaver.Dusongsong
 * @version: 1.0
 * @CreateDate: 2020-10-30
 * @Description: 金计划汇总审批流程需要计划任务每月固定日期触发生成，汇总条件为：在计划日期前到达资金计划申请流程的申请人确认节点
 * @ModifyLog:
 **/

public class WeaCreateZjjhhzbspCronJob extends BaseCronJob {
    @Override
    public void execute() {
        RecordSet rs = new RecordSet();
        RecordSet rs1 = new RecordSet();
        BaseBean baseBean = new BaseBean();
        String curdate = DateUtil.getCurrentDate();
        String curYearMonth = curdate.substring(0, 7);
        baseBean.writeLog(">>>>>WeaCreateZjjhhzbspCronJob>>>>>curdate=" + curdate);
        baseBean.writeLog(">>>>>WeaCreateZjjhhzbspCronJob>>>>>curYearMonth=" + curYearMonth);
        User user = new User(1);
        String formid = "396";
        String isnextflow = "1";
        String workflowid = Util.null2String(getWorkflowId("395").get("workflowid"));
        String nodeid = getNodeidByWfid(workflowid);
        baseBean.writeLog(">>>>>WeaCreateZjjhhzbspCronJob>>>>>nodeid=" + nodeid);
        rs.executeQuery("select sqrfb from formtable_main_395 where sqjhyf=? and dqrq<='" + curdate + "' group by sqrfb", curYearMonth);
        while (rs.next()) {
            List<Map<String, String>> field1List = new ArrayList<>();
            Map<String, String> mainMap = new HashMap<>();
            String sqrfb = Util.null2String(rs.getString("sqrfb"));
            mainMap.put("zjjhyf", curYearMonth);
            mainMap.put("sqrfb", sqrfb);
            List<Map<String, Object>> detailList = new ArrayList<>();
            Map<String, Object> detail1Map = new HashMap<>();
            detail1Map.put("tablename", "formtable_main_" + formid + "_dt1");
            rs1.executeQuery("select sqbm,requestid from formtable_main_395 where sqjhyf=? and dqrq<='" + curdate + "' and sqrfb=?", curYearMonth,sqrfb);
            while (rs1.next()) {
                Map<String, String> map = new HashMap<>();
                String requestid = Util.null2String(rs1.getString("requestid"));
                String sqbm = Util.null2String(rs1.getString("sqbm"));
                baseBean.writeLog(">>>>>WeaCreateZjjhhzbspCronJob>>>>>requestid=" + requestid);
                String nownodeid = getNownodeid(requestid);
                baseBean.writeLog(">>>>>WeaCreateZjjhhzbspCronJob>>>>>nownodeid=" + nownodeid);
                if (nodeid.equals(nownodeid)) {
                    map.put("sqbm", sqbm);
                    map.put("lcid", requestid);
                    map.put("sqrfb", sqrfb);
                    field1List.add(map);
                }
            }
            detail1Map.put("tablefield", field1List);
            detailList.add(detail1Map);
            baseBean.writeLog(">>>>>WeaCreateZjjhhzbspCronJob>>>>>detailList=" + detailList);
            Map<String, Object> resultMap = WorkflowCreateRequestId(user, formid, isnextflow, mainMap, detailList);
            baseBean.writeLog(">>>>>WeaCreateZjjhhzbspCronJob>>>>>resultMap=" + resultMap);
        }

    }

    private Map<String, Object> WorkflowCreateRequestId(User user, String formid, String isnextflow, Map<String, String> mainMap, List<Map<String, Object>> detailList) {
        BaseBean baseBean = new BaseBean();
        baseBean.writeLog(">>>>>WorkflowCreateRequestId>>>>>user=" + user);
        baseBean.writeLog(">>>>>WorkflowCreateRequestId>>>>>formid=" + formid);
        baseBean.writeLog(">>>>>WorkflowCreateRequestId>>>>>isnextflow=" + isnextflow);
        baseBean.writeLog(">>>>>WorkflowCreateRequestId>>>>>mainMap=" + mainMap);
        baseBean.writeLog(">>>>>WorkflowCreateRequestId>>>>>detailList=" + detailList);
        //主表数据
        ReqOperateRequestEntity requestParam = new ReqOperateRequestEntity();
        List<WorkflowRequestTableField> mainData = new ArrayList<>();
        for (Map.Entry<String, String> entry : mainMap.entrySet()) {
            WorkflowRequestTableField field = new WorkflowRequestTableField();
            field.setFieldName(entry.getKey());
            field.setFieldValue(entry.getValue());
            mainData.add(field);
        }
        requestParam.setMainData(mainData);
        //明细表数据
        if (!Objects.isNull(detailList)) {
            List<WorkflowDetailTableInfoEntity> detailData = new ArrayList<>();
            for (Map<String, Object> dtlmap : detailList) {
                String tablename = Util.null2String(dtlmap.get("tablename"));
                List<Map<String, String>> tableFieldList = (List<Map<String, String>>) dtlmap.get("tablefield");
                //设置明细信息
                WorkflowDetailTableInfoEntity detail1 = new WorkflowDetailTableInfoEntity();
                detail1.setTableDBName(tablename);
                //明细数据(多少条明细)
                WorkflowRequestTableRecord[] detailRows = new WorkflowRequestTableRecord[tableFieldList.size()];
                //遍历每一行明细
                int detailRowsIndex = 0;
                for (Map<String, String> map : tableFieldList) {
                    //明细行数据（每行有多少个字段）
                    WorkflowRequestTableField[] rowDatas = new WorkflowRequestTableField[map.size()];
                    int rowDatasIndex = 0;
                    //遍历明细每个字段
                    for (Map.Entry<String, String> detailMap : map.entrySet()) {
                        //行字段数据 （设置每个字段具体值）
                        WorkflowRequestTableField field1 = new WorkflowRequestTableField();
                        field1.setFieldName(detailMap.getKey());
                        field1.setFieldValue(detailMap.getValue());
                        rowDatas[rowDatasIndex++] = field1;
                    }        //封装某行明细数据
                    WorkflowRequestTableRecord row1 = new WorkflowRequestTableRecord();
                    row1.setRecordOrder(0);
                    row1.setWorkflowRequestTableFields(rowDatas);
                    detailRows[detailRowsIndex++] = row1;
                }
                //封装所有明细数据
                detail1.setWorkflowRequestTableRecords(detailRows);
                detailData.add(detail1);
            }
            requestParam.setDetailData(detailData);
        }
        Map<String, Object> otherParams = new HashMap<>();
        otherParams.put("isnextflow", isnextflow);
        requestParam.setOtherParams(otherParams);
        //固定创建流程id
        Map<String, String> wf = getWorkflowId(formid);
        requestParam.setWorkflowId(Util.getIntValue(wf.get("workflowid")));
        requestParam.setRequestName(Util.null2String(wf.get("workflowname")) + "-" + user.getUsername() + "-" + getDateTime());
        WorkflowRequestOperatePA operatePA = ServiceUtil.getService(WorkflowRequestOperatePAImpl.class);
        PAResponseEntity paResponseEntity = operatePA.doCreateRequest(user, requestParam);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.putAll((Map<String, Object>) paResponseEntity.getData());
        PAResponseCode paResponseCode = paResponseEntity.getCode();
        resultMap.put("message", paResponseCode.getMessage());
        resultMap.put("statuscode", paResponseCode.getStatusCode() + "");
        ReqFlowFailMsgEntity flowFailMsgEntity = paResponseEntity.getReqFailMsg();
        resultMap.putAll(paResponseEntity.getErrMsg());
        resultMap.putAll(flowFailMsgEntity.getMsgInfo());
        baseBean.writeLog(">>>>>WorkflowCreateRequestId>>>>>resultMap=" + resultMap);
        return resultMap;
    }

    private Map<String, String> getWorkflowId(String formid) {
        RecordSet rs = new RecordSet();
        Map<String, String> resultMap = new HashMap<>();
        rs.executeQuery("select (case when activeversionid is null then id else activeversionid end) from workflow_base " +
                "where abs(formid)=? group by (case when activeversionid is null then id else activeversionid end) ", formid);
        rs.next();
        String workflowid = Util.null2String(rs.getString(1));
        resultMap.put("workflowid", workflowid);
        rs.executeQuery("select workflowname from workflow_base where id=?", workflowid);
        rs.next();
        String workflowname = Util.null2String(rs.getString(1));
        resultMap.put("workflowname", workflowname);
        return resultMap;
    }

    private String getNodeidByWfid(String workflowid) {
        RecordSet rs = new RecordSet();
        rs.executeQuery(" select id from workflow_nodebase where nodename = '申请人确认' and id " +
                "in (select nodeid from workflow_flownode where workflowid =?)", workflowid);
        rs.next();
        return Util.null2String(rs.getString(1));
    }
    private String getNownodeid(String requestid) {
        RecordSet rs = new RecordSet();
        rs.executeQuery(" select nownodeid  from workflow_nownode where requestid=?", requestid);
        rs.next();
        return Util.null2String(rs.getString("nownodeid"));
    }
}
